<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { login, getUserProfile } from "@/api/index";
import {
  setToken,
  setUserInfo,
  setUserRole,
  isRememberMe,
  getRememberedUsername,
  getRememberedPassword,
  setRememberMe,
} from "@/utils/auth";
import { useMerchantStore } from "@/store";

const router = useRouter();
const merchantStore = useMerchantStore();

const loginForm = reactive({
  username: "",
  password: "",
  rememberMe: false,
});

const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 1, max: 50, message: "用户名长度1-50位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 128, message: "密码长度6-128位", trigger: "blur" },
  ],
});

const loginFormRef = ref<FormInstance>();
const loading = ref(false);

// 初始化时检查是否有保存的登录信息
onMounted(() => {
  if (isRememberMe()) {
    const savedUsername = getRememberedUsername();
    const savedPassword = getRememberedPassword();

    if (savedUsername) {
      loginForm.username = savedUsername;
    }

    if (savedPassword) {
      loginForm.password = savedPassword;
    }

    loginForm.rememberMe = true;
  }
});

// 检查用户身份是否为商家
const checkMerchantRole = (userInfo: any) => {
  if (!userInfo) return false;

  // 检查用户角色
  const role = userInfo.role?.toUpperCase() || "";

  // 根据您的系统，可能需要调整这里的判断条件
  return role === "MERCHANT" || role === "ROLE_MERCHANT" || role === "BUSINESS";
};

const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        console.log("开始登录请求，用户名:", loginForm.username);
        const res = await login({
          username: loginForm.username,
          password: loginForm.password,
        });

        // 详细输出响应数据结构，帮助调试
        console.log("完整响应对象:", res);
        console.log("响应数据:", res.data);
        console.log("响应状态:", res.status);

        // 获取响应数据
        const responseData = res.data;

        // 检查是否有错误信息
        const errorMsg =
          responseData.message ||
          responseData.msg ||
          (responseData.data &&
            (responseData.data.message || responseData.data.msg));

        // 使用status字段判断是否成功（HTTP状态码200表示成功）
        const isSuccess =
          res.status === 200 &&
          (responseData.status === 200 ||
            responseData.status === 0 ||
            responseData.code === 200 ||
            responseData.code === 0);

        if (!isSuccess && errorMsg) {
          ElMessage.error(`登录失败: ${errorMsg}`);
          loading.value = false;
          return;
        }

        // 提取token和用户信息
        let token = null;
        let userInfo: any = null;

        // 处理不同的API响应格式
        if (responseData.data && responseData.data.token) {
          // 嵌套的data结构
          token = responseData.data.token;
          userInfo = responseData.data.userInfo || responseData.data.user;
          console.log("从嵌套data中提取token:", token);
        } else if (responseData.token) {
          // 直接的token结构
          token = responseData.token;
          userInfo = responseData.userInfo || responseData.user;
          console.log("从直接结构中提取token:", token);
        } else {
          // 尝试在对象中查找token
          for (const key in responseData) {
            if (key === "token") {
              token = responseData[key];
              console.log("从对象中查找到token:", token);
            }
            if (key === "userInfo" || key === "user") {
              userInfo = responseData[key];
            }
          }
        }

        // 检查是否找到token
        if (!token) {
          console.error("未找到token字段:", responseData);
          ElMessage.error("登录失败：未获取到有效的登录信息");
          loading.value = false;
          return;
        }

        console.log("提取的用户信息:", userInfo);

        // 检查用户身份
        if (!checkMerchantRole(userInfo)) {
          console.log("用户角色验证失败，不是商家角色");
          ElMessage.error("登录失败：您不是商家，无权访问商家系统");
          loading.value = false;
          return;
        }

        // 处理记住密码
        if (loginForm.rememberMe) {
          console.log("设置记住密码");
          setRememberMe(loginForm.username, loginForm.password, true);
        } else {
          setRememberMe("", "", false);
        }

        // 存储token和用户信息
        console.log("存储token:", token);
        setToken(token, 7 * 24 * 60 * 60 * 1000); // 设置token过期时间为一周

        // 存储用户角色
        console.log("设置用户角色为merchant");
        setUserRole("merchant");

        // 存储用户信息
        if (userInfo) {
          console.log("存储用户信息");
          setUserInfo(userInfo);
        }

        ElMessage({
          message: "登录成功",
          type: "success",
          duration: 2000,
        });

        // 延迟跳转确保token存储完成
        setTimeout(() => {
          console.log("准备跳转到商家仪表盘");
          // 先跳转到仪表盘
          router
            .push("/merchant/dashboard")
            .then(() => {
              console.log("成功跳转到商家仪表盘");
              // 跳转成功后再获取店铺列表
              merchantStore.fetchStores(true).catch((err) => {
                console.error("获取店铺列表失败:", err);
              });
            })
            .catch((err) => {
              console.error("路由跳转失败:", err);
              ElMessage.error("页面跳转失败，请重试");
            });
        }, 800);
      } catch (e) {
        console.error("登录异常:", e);
        ElMessage.error("网络错误或服务器异常");
      } finally {
        loading.value = false;
      }
    }
  });
};

const goToRegister = () => {
  router.push("/merchant/register");
};

const goBack = () => {
  router.push("/");
};
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <el-button
        icon="Back"
        circle
        @click="goBack"
        class="back-btn"
      ></el-button>
      <div class="login-header">
        <img src="/logo.png" alt="饱了么" class="logo-image" />
        <h2>
          商家登录
          <span class="en-title">Merchant Login</span>
        </h2>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-position="top"
        class="login-form"
        @keyup.enter="handleLogin(loginFormRef)"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="User"
            class="tech-input"
            clearable
            maxlength="50"
            autocomplete="username"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            prefix-icon="Lock"
            show-password
            class="tech-input"
            maxlength="128"
            autocomplete="current-password"
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
        </el-form-item>

        <div class="form-actions">
          <el-button
            type="primary"
            @click="handleLogin(loginFormRef)"
            :loading="loading"
            class="login-btn"
          >
            登录
          </el-button>
        </div>

        <div class="form-links">
          <el-link @click="goToRegister">没有账号？点击注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
@import url("https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@500&display=swap");

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden !important;
  font-family: "Noto Serif SC", "阿里巴巴普惠体", "思源宋体", "微软雅黑",
    "Microsoft YaHei", Arial, sans-serif;
}

.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: linear-gradient(
      rgba(255, 224, 130, 0.82),
      rgba(255, 213, 79, 0.82)
    ),
    url("https://images.pexels.com/photos/70497/pexels-photo-70497.jpeg?auto=compress&w=900&q=80")
      center center/cover no-repeat;
  color: #222;
  font-family: "Noto Serif SC", "阿里巴巴普惠体", "思源宋体", "微软雅黑",
    "Microsoft YaHei", Arial, sans-serif;
}

.login-box {
  z-index: 1;
  width: 420px;
  padding: 2.5rem 2.5rem 2rem 2.5rem;
  background: rgba(255, 245, 200, 0.97);
  border-radius: 24px;
  box-shadow: 0 4px 24px 0 #90caf933;
  border: 2.5px solid #90caf9;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  color: #a05a1c;
}

.login-header {
  position: relative;
  text-align: center;
  margin-bottom: 2rem;
}
.login-header h2 {
  font-size: 2rem;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  color: #d2691e;
  letter-spacing: 0.08em;
  margin-bottom: 0.2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-header .en-title {
  font-size: 1rem;
  color: #bfa16b;
  font-family: "PingFang SC", Arial, sans-serif;
  margin-top: 0.1rem;
  letter-spacing: 0.12em;
  opacity: 0.85;
}

.back-btn {
  position: absolute;
  left: 0.8rem;
  top: 0.8rem;
  z-index: 2;
}

.login-form {
  margin-top: 1.5rem;
  width: 100%;
  color: #a05a1c;
}

.el-form-item__label {
  color: #ff9800;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.tech-input :deep(.el-input__wrapper) {
  background: #fffbe8;
  border: 1.5px solid #ffd600;
  border-radius: 14px;
  box-shadow: 0 2px 8px 0 #ffd60022;
  color: #222;
  font-size: 1.1rem;
  transition: border-color 0.3s, box-shadow 0.3s;
}
.tech-input :deep(.el-input__wrapper):focus-within {
  border-color: #ff9800;
  box-shadow: 0 0 0 2px #ffd60099, 0 0 12px 2px #ff980055;
}
.tech-input :deep(.el-input__inner) {
  background: transparent;
  color: #222;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.form-actions {
  margin-top: 1.5rem;
}

.login-btn {
  width: 100%;
  font-size: 1.1rem;
  background: linear-gradient(90deg, #fff700 0%, #ffd600 60%, #ff9800 100%);
  border: none;
  color: #fff;
  font-family: "PingFang SC", Arial, sans-serif;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 #ffd60055, 0 0 0 0 #fff;
  transition: background 0.3s, color 0.3s, box-shadow 0.3s;
  font-weight: 700;
  position: relative;
  overflow: hidden;
}
.login-btn::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  border-radius: 16px;
  background: linear-gradient(120deg, #fff 0%, transparent 80%);
  opacity: 0.18;
  pointer-events: none;
}
.login-btn:hover {
  background: linear-gradient(90deg, #fff700 0%, #ff9800 100%);
  color: #fffbe8;
  box-shadow: 0 4px 24px 0 #ffd60099, 0 0 0 0 #fff;
}

.form-links {
  margin-top: 1rem;
  text-align: center;
  color: #a05a1c;
}

.logo-image {
  width: 60px;
  height: 60px;
  margin-bottom: 1rem;
}
</style>
